/*****************************
 * Copyright (c) 2009 by  Co. Ltd.  All rights reserved.
 ****************************/
package com.happy.action.message;

import java.util.Date;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.core.orm.hibernate.Page;
import com.core.orm.hibernate.SpringSecurityUtils;
import com.core.web.struts2.CRUDActionSupport;
import com.happy.common.util.AppConstants;
import com.happy.entity.Message;
import com.happy.entity.User;
import com.happy.entity.UserInfo;
import com.happy.exception.ServicesException;
import com.happy.services.MessageService;
import com.happy.services.UserInfoServices;
import com.happy.services.UserServices;

/**
 * @{# MessageAction.java
 *     <p>
 *     MessageAction:站内短消息,查看短消息，发送短消息，回复短消息
 *     </p>
 * @author <a href="mailto:happyMpl@163.com">毛鹏霖</a>
 * @version v 0.1
 */

public class MessageAction extends CRUDActionSupport<Message> {

	/**
	 * {@value}
	 */
	private static final long serialVersionUID = 2208511276083910072L;
	@Autowired
	private MessageService pubMessageManager;
	private Page<Message> reciveMssageg = new Page<Message>(15, true);
	private int currentPage = 1;
	private int pageSize = 10;
	private Message message;
	private Long messageId;// 短消息编号
	@Autowired
	private UserInfoServices baseUserinfoManager;
	@Autowired
	private UserServices userServices;
	private int messageNotReadCount = 0;// 未读短消息记录数
	private UserInfo userInfo;// 此信息的发送人
	private String sendUserId = null;
	private Page<Message> sendMsg = new Page<Message>(10, true);// 我发送的短消息集合
	private String reciveName;// 页面上收信人帐号
	private String title;// 消息标题
	private String content;// 消息内容

	private String reciveUserId = null;
	private boolean flag = false;// 显示是否可以回复，标识

	public Message getModel() {
		return message;
	}

	public void prepare() throws Exception {

		if (message == null)
			message = new Message();
	}

	@Override
	protected void prepareModel() throws Exception {

	}

	@Override
	/**
	 * 删除短消息
	 */
	public String delete() throws Exception {

		logger.info("当前要删除的消息是" + messageId);
		Message msg = pubMessageManager.getPubMessage(messageId);
		if (msg.getNuReceiveUserId().equals(
				SpringSecurityUtils.getCurrentUserName())) {
			pubMessageManager.deleteMessage(messageId);
			return "delete";
		} else {
			throw new ServicesException("消息读取错误");
		}

	}

	public String list() throws Exception {

		reciveMssageg.setPageNo(currentPage);
		reciveMssageg.setPageSize(pageSize);
		reciveMssageg.setTotalCount(pubMessageManager
				.getMessageCountByReceiveUser(SpringSecurityUtils
						.getCurrentUserName()));
		sendMsg.setPageNo(currentPage);// 我发送的短消息

		sendMsg.setTotalCount(pubMessageManager
				.getMessageCountBySendUser(SpringSecurityUtils
						.getCurrentUserName()));

		sendMsg = pubMessageManager.getMessageBySendUser(sendMsg,
				SpringSecurityUtils.getCurrentUserName());// 未读短消息
		messageNotReadCount = pubMessageManager
				.getMesssageNotReadByReceiveUser(SpringSecurityUtils
						.getCurrentUserName());
		reciveMssageg = pubMessageManager.getMessageByReceiveUser(
				reciveMssageg, SpringSecurityUtils.getCurrentUserName());

		return SUCCESS;
	}

	/**
	 * 分页查询短消息 我收到的短消息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String ajax() throws Exception {
		reciveMssageg.setPageNo(currentPage);
		// UserInfo
		// uf=baseUserinfoManager.getByUserId(userServices.getUserByName(SpringSecurityUtils.getCurrentUserName()).getId());
		try {
			reciveMssageg = pubMessageManager.getMessageByReceiveUser(
					reciveMssageg, SpringSecurityUtils.getCurrentUserName());
		} catch (Exception e) {
			return "login";
		}
		JSONArray jArray = JSONArray.fromObject(reciveMssageg);
		ServletActionContext.getResponse().setCharacterEncoding("utf-8");
		ServletActionContext.getResponse().getWriter().print(jArray.toString());
		return null;
	}

	/**
	 * 分页查询 我发送的短消息
	 * 
	 * @return
	 * @throws Exception
	 */
	public String secondAjax() throws Exception {
		try {
			// UserInfo
			// uf=baseUserinfoManager.getByUserId(userServices.getUserByName(SpringSecurityUtils.getCurrentUserName()).getId());
			sendMsg.setPageNo(currentPage);
			sendMsg.setTotalCount(pubMessageManager
					.getMessageCountBySendUser(SpringSecurityUtils
							.getCurrentUserName()));
			sendMsg = pubMessageManager.getMessageBySendUser(sendMsg,
					SpringSecurityUtils.getCurrentUserName());
			JSONArray jArray = JSONArray.fromObject(sendMsg);
			ServletActionContext.getResponse().setCharacterEncoding("utf-8");
			ServletActionContext.getResponse().getWriter().print(
					jArray.toString());
		} catch (Exception e) {
			return "login";
		}
		return null;
	}

	@Override
	/**
	 * 发送短消息
	 */
	public String save() throws Exception {
		logger.info("========发送短消息=====");

		Message messages = new Message();
		messages.setDate(new Date());// 设置发送日期为当前系统日期
		try {

			messages.setNuSendUserId(SpringSecurityUtils.getCurrentUserName());
		} catch (Exception e) {
			addActionError("短消息发送失败:本系统不允许发送匿名短消息");
			logger.info("发送短消息失败：当前用户未登录  messageAction save mehtod"
					+ e.getMessage());
			return "errors";
		}

		// 如果收信人的编号为空
		if (reciveUserId == null) {
			try {
				logger.info("收信人编号为空:正在发送新的短消息");
				User u = userServices.getUserByName(reciveName);
				if (u == null)
					throw new Exception("");
				else
					messages.setNuReceiveUserId(reciveName);
			} catch (Exception e) {
				System.out.println("出现异常了:收信人查找失败 查无此人" + e.getMessage());
				return "save";
			}
			messages.setVcTitle(title);
		} else {// 否则为短消息回复
			messages.setVcTitle("回复:"
					+ SpringSecurityUtils.getCurrentUserName());
			messages.setNuReceiveUserId(reciveUserId);
		}
		messages.setChStatus(AppConstants.MESSAGE_NOT_READ);// 默认设置短消息的状体啊 未读短消息
		messages.setNuMsgType("1");// 默认类型为1 3为系统信息
		try {

			messages.setVcContent(content);

			pubMessageManager.sendMessage(messages);
			logger.info("短消息发送成功");
		} catch (RuntimeException e) {
			logger.info("消息发送失败：messageAction save" + e.getMessage());
			addActionError("短消息发送失败:" + e.getMessage());
			return "errors";
		}

		return "save";
	}

	public String whoSendMe() throws Exception {
		// UserInfo
		// uf=baseUserinfoManager.getByUserId(userServices.getUserByName(SpringSecurityUtils.getCurrentUserName()).getId());
		sendMsg.setPageNo(currentPage);// 我发送的短消息
		sendMsg.setTotalCount(pubMessageManager
				.getMessageCountBySendUser(SpringSecurityUtils
						.getCurrentUserName()));

		sendMsg = pubMessageManager.getMessageBySendUser(sendMsg,
				SpringSecurityUtils.getCurrentUserName());// 未读短消息
		messageNotReadCount = pubMessageManager
				.getMesssageNotReadByReceiveUser(SpringSecurityUtils
						.getCurrentUserName());
		return "who";
	}

	public String send() throws Exception {
		// UserInfo
		// uf=baseUserinfoManager.getByUserId(userServices.getUserByName(SpringSecurityUtils.getCurrentUserName()).getId());
		messageNotReadCount = pubMessageManager
				.getMesssageNotReadByReceiveUser(SpringSecurityUtils
						.getCurrentUserName());
		return "send";
	}

	/**
	 * @return
	 * 
	 *         <pre>
	 *   detailMessage:查看短消息详情
	 * </pre>
	 */
	public String detailMessage() throws Exception {

		// UserInfo
		// uf=baseUserinfoManager.getByUserId(userServices.getUserByName(SpringSecurityUtils.getCurrentUserName()).getId());
		message = pubMessageManager.getPubMessage(messageId);

		if (message.getNuReceiveUserId().equals(
				SpringSecurityUtils.getCurrentUserName())) {
			messageNotReadCount = pubMessageManager
					.getMesssageNotReadByReceiveUser(SpringSecurityUtils
							.getCurrentUserName());
			message = pubMessageManager.getPubMessage(messageId);
			message.setChStatus(AppConstants.MESSAGE_IS_READ);
			pubMessageManager.sendMessage(message);
		} else {
			throw new ServicesException("消息读取错误");
		}

		return "myMessage";
	}

	public Page<Message> getReciveMssageg() {
		return reciveMssageg;
	}

	public void setReciveMssageg(Page<Message> reciveMssageg) {
		this.reciveMssageg = reciveMssageg;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public Message getMessage() {
		return message;
	}

	public void setMessage(Message message) {
		this.message = message;
	}

	public Long getMessageId() {
		return messageId;
	}

	public void setMessageId(Long messageId) {
		this.messageId = messageId;
	}

	public int getMessageNotReadCount() {
		return messageNotReadCount;
	}

	public void setMessageNotReadCount(int messageNotReadCount) {
		this.messageNotReadCount = messageNotReadCount;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public String getSendUserId() {
		return sendUserId;
	}

	public Page<Message> getSendMsg() {
		return sendMsg;
	}

	public void setSendMsg(Page<Message> sendMsg) {
		this.sendMsg = sendMsg;
	}

	public String getReciveName() {
		return reciveName;
	}

	public void setReciveName(String reciveName) {
		this.reciveName = reciveName;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getReciveUserId() {
		return reciveUserId;
	}

	public void setReciveUserId(String reciveUserId) {
		this.reciveUserId = reciveUserId;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public void setSendUserId(String id) {
		this.sendUserId = id;
	}

}
